package pers.mine.controller;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import pers.mine.po.GoodsItem;
import pers.mine.po.Member;
import pers.mine.po.Order;
import pers.mine.service.inter.CheckOutService;
import pers.mine.service.inter.GoodsItemService;
import pers.mine.service.inter.MemberService;
import pers.mine.vo.Cart;
import pers.mine.vo.Info;

/**
 * 订单Controller 用于完成订单信息生成,提交等操作
 * 
 * @author Mine
 * @since 2016年10月23日_下午8:47:57
 */
@Controller
@RequestMapping("/order")
@Scope("session")
public class OrderController {
	private Info indexinfo = new Info();// 放到首页的信息
	@Autowired
	CheckOutService checkOutService;
	@Autowired
	GoodsItemService goodsItemService;
	@Autowired
	MemberService memberService;

	/**
	 * [生成订单]几种情况: >> a. [tempOrder]不为空,存在未处理订单,提示用户,让用户选择 b.
	 * [tempOrder]为空,不存在未处理订单 1). 直接购买某商品:生成一个只有一项商品的购物车,作为结账购物车 2).
	 * 结账购物车:将当前购物车作为结账购物车,生成后购物车将清空
	 * 
	 * >>{生成订单} 使用[member]和[结账购物车]生成订单并显示
	 * 
	 * ps:[tempOrder]作为要结账的未付款订单保存在session中,在结账完成后,清空session
	 * 系统策略是要生成新订单必须先处理完未处理订单,[tempOrder]主要是考虑到有订单生成但未提交的情况
	 */
	@RequestMapping(value = "/build")
	public String buildOneOrder(Integer gid, Integer num, String oper,
			Model model, HttpSession session) {
		// 先判断member是不是存在
		Object objMe = session.getAttribute("member");
		indexinfo.setCanChange(false);
		if (objMe == null) {
			indexinfo.setType(Info.ERROR);
			indexinfo.setMsg("[错误的操作]:还没有登录...");
			model.addAttribute("indexinfo", indexinfo);
			return "forward:/indexshow";
		}
		Member member = (Member) objMe;
		/**
		 * 判断是否存在未处理订单
		 */
		Object objOrder = session.getAttribute("tempOrder");
		if (objOrder != null) {// 存在
			indexinfo.setType(Info.ERROR);
			indexinfo.setMsg("[订单构建失败]:存在未处理订单,请先处理该订单...");
			model.addAttribute("indexinfo", indexinfo);
			indexinfo = new Info();
			return "forward:/indexshow";
		}
		Cart tempCart = null;
		// 依据oper属性值选择初始化tempCart
		if (oper != null && "justBuyOne".equals(oper.trim())) {// 直接购买单项商品
			if (baseVali(gid, num)) {// 基本验证通过
										// 根据id获取商品最新信息
				GoodsItem one = goodsItemService.getOneGoodsItemByID(gid);
				tempCart = new Cart();
				tempCart.put(one, num);
			}
		} else if (oper != null && "checkoutCart".equals(oper.trim())) {// 结账购物车
			Object objCart = session.getAttribute("cartInfo");
			if (objCart != null) {
				tempCart = (Cart) objCart;
			}
		}
		if (tempCart == null || tempCart.getNumSum() <= 0) {
			indexinfo.setType(Info.ERROR);
			indexinfo.setMsg("[订单构建失败]:生成订单参数不完整{商品数量不合法或购物车为空}...");
			model.addAttribute("indexinfo", indexinfo);
			indexinfo = new Info();
			return "forward:/indexshow";
		}
		// tempCart合法,执行数据库验证,余额不验证,返回未付款订单
		Order tempOrder = checkOutService.doCheck(member.getId(), tempCart,
				false);
		if (tempOrder == null) {
			indexinfo.setType(Info.ERROR);
			indexinfo
					.setMsg("[订单构建失败]:可能原因有{商品库存不足,商品已下架,用户id不可用,用户联系方式/地址不合法}等...");
			model.addAttribute("indexinfo", indexinfo);
			indexinfo = new Info();
			return "forward:/indexshow";
		} else {// 生成订单成功
			System.out.println(tempOrder);
			if ("checkoutCart".equals(oper.trim())) {// 如果是购物车生成,清空该购物车session
				session.removeAttribute("cartInfo");
			}
			indexinfo.setCanChange(true);
			session.setAttribute("tempOrder", tempOrder);// 放入session
			return "redirect:show";
		}
	}

	@RequestMapping(value = "/show")
	public String showTempOrder(Model model, HttpServletRequest req) {
		Object obj = req.getAttribute("indexinfo");
		if (obj != null) {
			indexinfo = (Info) obj;
		}
		if (indexinfo.isCanChange()) {
			indexinfo.setType(Info.INFO);
			indexinfo.setMsg("[未处理订单]:在这里你可以给订单付款...");
		}
		model.addAttribute("indexinfo", indexinfo);
		indexinfo.setCanChange(true);
		return "member/oneOrder";
	}

	/**
	 * 放弃订单操作
	 */
	@RequestMapping(value = "/giveup")
	public String giveup(Model model, HttpSession session) {
		Object objOrder = session.getAttribute("tempOrder");
		if (objOrder == null) {
			indexinfo.setType(Info.ERROR);
			indexinfo.setMsg("不存在未处理订单...");
		} else {
			// session.setAttribute("tempOrder", null); //都可以删除吧
			session.removeAttribute("tempOrder");

			indexinfo.setType(Info.SUCCESS);
			indexinfo.setMsg("已放弃订单...");
		}
		indexinfo.setCanChange(false);
		model.addAttribute("indexinfo", indexinfo);
		indexinfo = new Info();
		return "forward:/indexshow";
	}

	/**
	 * 付款订单操作
	 * 
	 * @throws SQLException
	 */
	@RequestMapping(value = "/checkout")
	public String checkout(String payKey, Model model, HttpSession session)
			throws SQLException {
		// 获取member以及未处理订单
		Object objOrder = session.getAttribute("tempOrder");
		Object objmember = session.getAttribute("member");
		Member member = null;
		Member dbMember = null;
		Order tempOrder = null;
		if (objOrder != null && objmember != null) {
			tempOrder = (Order) objOrder;
			member = (Member) objmember;
			if (member.getId().intValue() == tempOrder.getMid().intValue()) {
				if (payKey == null || "".equals(payKey.trim())) {
					indexinfo.setType(Info.ERROR);
					indexinfo.setCanChange(false);
					indexinfo.setMsg("[验证信息]:支付密码不能为空...");
					model.addAttribute("indexinfo", indexinfo);
					return "forward:show";
				}
				dbMember = memberService.getOneMemberByID(member.getId());
				if (dbMember != null && dbMember.getState() == 1
						&& payKey.equals(dbMember.getPw())) {
					// 密码正确，执行付款操作
					if (checkOutService.checkOut(tempOrder)) {
						indexinfo.setType(Info.SUCCESS);
						indexinfo.setMsg("[付款信息]:订单提交成功,可前往个人信息中查看...");
						// 删除未处理订单信息session
						session.removeAttribute("tempOrder");
						// 更新余额
						Member newMember = memberService
								.getOneMemberByID(member.getId());
						if (newMember != null) {
							session.setAttribute("member", newMember);
						}
					} else {
						indexinfo.setType(Info.ERROR);
						indexinfo.setMsg("[付款信息]:订单提交失败{商品库存不足或者余额不足}...");
					}
					indexinfo.setCanChange(false);
					model.addAttribute("indexinfo", indexinfo);
					indexinfo = new Info();
					return "forward:/indexshow";
				} else {
					indexinfo.setType(Info.ERROR);
					indexinfo.setMsg("[验证信息]:支付密码错误...");
					indexinfo.setCanChange(false);
					model.addAttribute("indexinfo", indexinfo);
					return "forward:show";
				}
			}
		}
		indexinfo.setCanChange(false);
		indexinfo.setType(Info.ERROR);
		indexinfo.setMsg("[验证信息]:尚未登录或者订单不存在...");
		model.addAttribute("indexinfo", indexinfo);
		indexinfo = new Info();
		return "forward:/indexshow";
	}

	private boolean baseVali(Integer oneId, Integer oneNum) {
		// 数据合法性检测
		if (oneId == null || oneId < 1) {
			return false;
		}
		if (oneNum == null || oneNum < 1) {
			return false;
		}
		return true;
	}

}
